package com.boyon.web.servlet.tomcat;

import javax.servlet.Servlet;

import org.apache.catalina.startup.Tomcat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.condition.SearchStrategy;
import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration.BeanPostProcessorsRegistrar;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;

import com.boyon.redis.adapter.JedisAdapter;
import com.boyon.redis.factory.JedisFactory;

import redis.clients.jedis.JedisPoolConfig;

/**
 * ClassName:TomcatContainerConfiguration <br/>
 * Function: tomcat servlet容器. <br/>
 * Date: 2018年3月26日 下午8:48:52 <br/>
 * 
 * @author sunshulin
 * @version
 * @since JDK 1.8
 * @see
 */
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@ConditionalOnWebApplication
@Import(BeanPostProcessorsRegistrar.class)
public class TomcatContainerConfiguration {

	@Configuration
	@ConditionalOnClass({ Servlet.class, Tomcat.class })
	@ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search = SearchStrategy.CURRENT)
	public static class EmbeddedTomcat {

		@Value("${redis.session.type}")
		private Integer redisType;
		@Value("${redis.session.hosts}")
		private String hosts;
		@Value("${redis.session.master}")
		private String master;
		@Value("${redis.session.credit}")
		private String credit;

		@Bean(value = "sessionRedis")
		public JedisAdapter jedisAdapter() {
			JedisFactory factory = new JedisFactory(new JedisPoolConfig(),
					hosts, master, credit, redisType);
			return factory.getJedisAdapter();
		}

		@Bean
		public TomcatManager tomcatManager(
				@Autowired @Qualifier(value = "sessionRedis") JedisAdapter jedisAdapter) {
			TomcatManager tomcatManager = new TomcatManager(jedisAdapter);
			return tomcatManager;
		}

		@Bean
		public TomcatContainerFactory tomcatEmbeddedServletContainerFactory(
				TomcatManager manager) {
			TomcatContainerFactory tomcatContainerFactory = new TomcatContainerFactory(
					manager);
			return tomcatContainerFactory;
		}

	}
}
